// 获取卡券列表
async function getCoupons(request, reply) {
  try {
    const { type, status, storeId, page = 1, pageSize = 10 } = request.query;
    
    // 构建查询条件
    const where = {};
    if (type) where.type = type;
    if (status) where.status = status;
    if (storeId) {
      const id = parseInt(storeId, 10);
      if (!isNaN(id)) {
        where.storeId = id;
      }
    }

    // 计算分页
    const skip = (page - 1) * pageSize;
    
    // 查询数据
    const [total, list] = await Promise.all([
      request.server.prisma.voucher.count({ where }),
      request.server.prisma.voucher.findMany({
        where,
        skip,
        take: pageSize,
        orderBy: { createdAt: 'desc' },
        include: {
          store: {
            select: {
              name: true
            }
          },
          seatTypeLimits: true // 包含座位类型限制
        }
      })
    ]);

    // 格式化返回数据
    const formattedList = list.map(voucher => ({
      ...voucher,
      shopName: voucher.store ? voucher.store.name : '全店铺通用',
      seatTypes: voucher.seatTypeLimits.map(limit => limit.seatType) // 格式化座位类型
    }));

    return {
      code: 200,
      data: {
        total,
        list: formattedList
      }
    };
  } catch (error) {
    request.log.error(error);
    return reply.code(500).send({
      code: 500,
      message: '获取卡券列表失败'
    });
  }
}

// 创建卡券
async function createCoupon(request, reply) {
  try {
    const {
      name,
      type,
      value,
      storeId,
      validStartTime,
      validEndTime,
      minConsume,
      stock,
      isPaid,
      price,
      isOneTime,
      description,
      instruction,
      seatTypes
    } = request.body;

    // 如果提供了storeId，验证店铺是否存在
    if (storeId) {
      const id = parseInt(storeId, 10);
      if (isNaN(id)) {
        return reply.code(400).send({
          code: 400,
          message: '无效的店铺ID'
        });
      }
      const store = await request.server.prisma.store.findUnique({
        where: { id }
      });
      if (!store) {
        return reply.code(400).send({
          code: 400,
          message: '店铺不存在'
        });
      }
    }

    // 验证日期格式
    let startDate, endDate;
    try {
      startDate = new Date(validStartTime);
      endDate = new Date(validEndTime);
      
      // 检查日期是否有效
      if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
        return reply.code(400).send({
          code: 400,
          message: '无效的日期格式'
        });
      }

      // 检查结束时间是否晚于开始时间
      if (endDate <= startDate) {
        return reply.code(400).send({
          code: 400,
          message: '结束时间必须晚于开始时间'
        });
      }
    } catch (error) {
      return reply.code(400).send({
        code: 400,
        message: '日期格式错误'
      });
    }

    // 创建卡券
    await request.server.prisma.voucher.create({
      data: {
        name,
        type,
        value: parseFloat(value),
        storeId: storeId ? parseInt(storeId, 10) : null,
        validStartTime: startDate,
        validEndTime: endDate,
        minConsume: minConsume ? parseFloat(minConsume) : null,
        stock: parseInt(stock, 10),
        isPaid: Boolean(isPaid),
        price: parseFloat(price),
        isOneTime: Boolean(isOneTime),
        description: description || '',
        instruction: instruction || '',
        status: '下架',
        isActive: true,
        createdAt: new Date(),
        seatTypeLimits: seatTypes ? {
          create: seatTypes.map(type => ({ seatType: type }))
        } : undefined
      }
    });

    return {
      code: 200,
      message: '创建卡券成功'
    };
  } catch (error) {
    request.log.error(error);
    return reply.code(500).send({
      code: 500,
      message: '创建卡券失败'
    });
  }
}

// 更新卡券状态
async function updateCouponStatus(request, reply) {
  try {
    const { id } = request.params;
    const { status } = request.body;

    // 验证状态值
    if (!['上架', '下架'].includes(status)) {
      return reply.code(400).send({
        code: 400,
        message: '无效的状态值'
      });
    }

    // 将 id 转换为整数
    const voucherId = parseInt(id, 10);
    if (isNaN(voucherId)) {
      return reply.code(400).send({
        code: 400,
        message: '无效的卡券ID'
      });
    }

    // 更新状态
    const voucher = await request.server.prisma.voucher.update({
      where: { id: voucherId },
      data: { 
        status,
        updatedAt: new Date()
      }
    });

    return {
      code: 200,
      message: '更新卡券状态成功'
    };
  } catch (error) {
    if (error.code === 'P2025') {
      return reply.code(404).send({
        code: 404,
        message: '卡券不存在'
      });
    }
    request.log.error(error);
    return reply.code(500).send({
      code: 500,
      message: '更新卡券状态失败'
    });
  }
}

// 获取单个卡券详情
async function getCouponDetail(request, reply) {
  try {
    const { id } = request.params;

    // 将 id 转换为整数
    const voucherId = parseInt(id, 10);
    if (isNaN(voucherId)) {
      return reply.code(400).send({
        code: 400,
        message: '无效的卡券ID'
      });
    }

    const voucher = await request.server.prisma.voucher.findUnique({
      where: { id: voucherId },
      include: {
        store: {
          select: {
            name: true
          }
        },
        seatTypeLimits: true
      }
    });

    if (!voucher) {
      return reply.code(404).send({
        code: 404,
        message: '卡券不存在'
      });
    }

    return {
      code: 200,
      data: {
        ...voucher,
        shopName: voucher.store ? voucher.store.name : '全店铺通用',
        seatTypes: voucher.seatTypeLimits.map(limit => limit.seatType)
      }
    };
  } catch (error) {
    request.log.error(error);
    return reply.code(500).send({
      code: 500,
      message: '获取卡券详情失败'
    });
  }
}

// 更新卡券信息
async function updateCoupon(request, reply) {
  try {
    const { id } = request.params;
    const updateData = request.body;
    const { seatTypes, ...otherData } = updateData;

    // 将 id 转换为整数
    const voucherId = parseInt(id, 10);
    if (isNaN(voucherId)) {
      return reply.code(400).send({
        code: 400,
        message: '无效的卡券ID'
      });
    }

    // 如果更新了店铺ID，验证店铺是否存在
    if (otherData.storeId) {
      const storeId = parseInt(otherData.storeId, 10);
      if (isNaN(storeId)) {
        return reply.code(400).send({
          code: 400,
          message: '无效的店铺ID'
        });
      }
      const store = await request.server.prisma.store.findUnique({
        where: { id: storeId }
      });
      if (!store) {
        return reply.code(400).send({
          code: 400,
          message: '店铺不存在'
        });
      }
      otherData.storeId = storeId;
    }

    // 处理数值类型字段
    if (otherData.value) otherData.value = parseFloat(otherData.value);
    if (otherData.price) otherData.price = parseFloat(otherData.price);
    if (otherData.minConsume) otherData.minConsume = parseFloat(otherData.minConsume);
    if (otherData.stock) otherData.stock = parseInt(otherData.stock, 10);

    // 处理布尔类型字段
    if (typeof otherData.isPaid !== 'undefined') otherData.isPaid = Boolean(otherData.isPaid);
    if (typeof otherData.isOneTime !== 'undefined') otherData.isOneTime = Boolean(otherData.isOneTime);
    if (typeof otherData.isActive !== 'undefined') otherData.isActive = Boolean(otherData.isActive);

    // 处理日期字段
    if (otherData.validStartTime) {
      otherData.validStartTime = new Date(otherData.validStartTime);
    }
    if (otherData.validEndTime) {
      otherData.validEndTime = new Date(otherData.validEndTime);
    }

    // 添加更新时间
    otherData.updatedAt = new Date();

    // 更新卡券信息
    const voucher = await request.server.prisma.voucher.update({
      where: { id: voucherId },
      data: {
        ...otherData,
        seatTypeLimits: seatTypes ? {
          deleteMany: {},
          create: seatTypes.map(type => ({ seatType: type }))
        } : undefined
      }
    });

    return {
      code: 200,
      message: '更新卡券信息成功'
    };
  } catch (error) {
    if (error.code === 'P2025') {
      return reply.code(404).send({
        code: 404,
        message: '卡券不存在'
      });
    }
    request.log.error(error);
    return reply.code(500).send({
      code: 500,
      message: '更新卡券信息失败'
    });
  }
}

// 用户领取卡券
async function claimCoupon(request, reply) {
  try {
    const { voucherId } = request.body;
    const userId = request.user.id; // 从JWT中获取用户ID

    // 验证卡券ID
    const voucherIdInt = parseInt(voucherId, 10);
    if (isNaN(voucherIdInt)) {
      return reply.code(400).send({
        code: 400,
        message: '无效的卡券ID'
      });
    }

    // 查询卡券信息
    const voucher = await request.server.prisma.voucher.findUnique({
      where: { id: voucherIdInt }
    });

    if (!voucher) {
      return reply.code(404).send({
        code: 404,
        message: '卡券不存在'
      });
    }

    // 检查卡券状态
    if (voucher.status !== '上架') {
      return reply.code(400).send({
        code: 400,
        message: '卡券未上架，无法领取'
      });
    }

    // 检查卡券是否在有效期内
    const now = new Date();
    if (now < voucher.validStartTime || now > voucher.validEndTime) {
      return reply.code(400).send({
        code: 400,
        message: '卡券不在有效期内'
      });
    }

    // 检查库存
    if (voucher.stock <= 0) {
      return reply.code(400).send({
        code: 400,
        message: '卡券库存不足'
      });
    }

    // 检查是否仅限领取一次
    if (voucher.isOneTime) {
      const existingRecord = await request.server.prisma.voucherIssuedRecord.findFirst({
        where: {
          voucherId: voucherIdInt,
          userId: userId
        }
      });

      if (existingRecord) {
        return reply.code(400).send({
          code: 400,
          message: '该卡券仅限领取一次，您已领取过'
        });
      }
    }

    // 如果是付费卡券，检查用户余额
    if (voucher.isPaid) {
      const user = await request.server.prisma.user.findUnique({
        where: { id: userId }
      });

      if (user.balance < voucher.price) {
        return reply.code(400).send({
          code: 400,
          message: '余额不足，无法购买该卡券'
        });
      }
    }

    // 使用事务确保数据一致性
    const result = await request.server.prisma.$transaction(async (prisma) => {
      // 创建发放记录
      const issuedRecord = await prisma.voucherIssuedRecord.create({
        data: {
          voucherId: voucherIdInt,
          userId: userId,
          isPaid: voucher.isPaid,
          price: voucher.isPaid ? voucher.price : null
        }
      });

      // 减少库存
      await prisma.voucher.update({
        where: { id: voucherIdInt },
        data: { stock: voucher.stock - 1 }
      });

      // 如果是付费卡券，扣除用户余额
      if (voucher.isPaid) {
        await prisma.user.update({
          where: { id: userId },
          data: { balance: { decrement: voucher.price } }
        });
      }

      return issuedRecord;
    });

    return {
      code: 200,
      message: voucher.isPaid ? '购买卡券成功' : '领取卡券成功',
      data: {
        issuedRecordId: result.id,
        voucherName: voucher.name,
        voucherValue: voucher.value,
        validStartTime: voucher.validStartTime,
        validEndTime: voucher.validEndTime
      }
    };
  } catch (error) {
    request.log.error(error);
    return reply.code(500).send({
      code: 500,
      message: '领取卡券失败'
    });
  }
}

// 获取用户已领取的卡券列表
async function getUserCoupons(request, reply) {
  try {
    const userId = request.user.id;
    const { status, page = 1, pageSize = 10 } = request.query;

    // 构建查询条件
    const where = {
      userId: userId
    };

    // 计算分页
    const skip = (page - 1) * pageSize;

    // 查询用户的卡券记录
    const [total, records] = await Promise.all([
      request.server.prisma.voucherIssuedRecord.count({ where }),
      request.server.prisma.voucherIssuedRecord.findMany({
        where,
        skip,
        take: pageSize,
        orderBy: { createdAt: 'desc' },
        include: {
          voucher: {
            include: {
              store: {
                select: {
                  name: true
                }
              },
              seatTypeLimits: true
            }
          }
        }
      })
    ]);

    // 格式化返回数据
    const formattedList = records.map(record => ({
      id: record.id,
      voucherId: record.voucherId,
      voucherName: record.voucher.name,
      voucherType: record.voucher.type,
      voucherValue: record.voucher.value,
      isPaid: record.isPaid,
      price: record.price,
      validStartTime: record.voucher.validStartTime,
      validEndTime: record.voucher.validEndTime,
      minConsume: record.voucher.minConsume,
      description: record.voucher.description,
      instruction: record.voucher.instruction,
      shopName: record.voucher.store ? record.voucher.store.name : '全店铺通用',
      seatTypes: record.voucher.seatTypeLimits.map(limit => limit.seatType),
      claimTime: record.createdAt,
      // 计算卡券状态
      status: getVoucherStatus(record.voucher.validStartTime, record.voucher.validEndTime)
    }));

    return {
      code: 200,
      data: {
        total,
        list: formattedList
      }
    };
  } catch (error) {
    request.log.error(error);
    return reply.code(500).send({
      code: 500,
      message: '获取用户卡券列表失败'
    });
  }
}

// 使用卡券
async function useCoupon(request, reply) {
  try {
    const { voucherId, orderId, amount } = request.body;
    const userId = request.user.id;

    // 验证参数
    const voucherIdInt = parseInt(voucherId, 10);
    const orderIdInt = orderId ? parseInt(orderId, 10) : null;
    const amountFloat = parseFloat(amount);

    if (isNaN(voucherIdInt) || isNaN(amountFloat)) {
      return reply.code(400).send({
        code: 400,
        message: '无效的参数'
      });
    }

    // 查询卡券发放记录
    const issuedRecord = await request.server.prisma.voucherIssuedRecord.findFirst({
      where: {
        voucherId: voucherIdInt,
        userId: userId
      },
      include: {
        voucher: true
      }
    });

    if (!issuedRecord) {
      return reply.code(404).send({
        code: 404,
        message: '您未领取该卡券'
      });
    }

    const voucher = issuedRecord.voucher;

    // 检查卡券是否在有效期内
    const now = new Date();
    if (now < voucher.validStartTime || now > voucher.validEndTime) {
      return reply.code(400).send({
        code: 400,
        message: '卡券已过期或未到使用时间'
      });
    }

    // 检查使用金额是否满足最低消费要求
    if (voucher.minConsume && amountFloat < voucher.minConsume) {
      return reply.code(400).send({
        code: 400,
        message: `使用金额不足，最低消费${voucher.minConsume}元`
      });
    }

    // 检查使用金额是否超过卡券面值
    if (amountFloat > voucher.value) {
      return reply.code(400).send({
        code: 400,
        message: `使用金额超过卡券面值，卡券面值为${voucher.value}元`
      });
    }

    // 创建使用记录
    const usedRecord = await request.server.prisma.voucherUsedRecord.create({
      data: {
        voucherId: voucherIdInt,
        userId: userId,
        orderId: orderIdInt,
        amount: amountFloat
      }
    });

    return {
      code: 200,
      message: '使用卡券成功',
      data: {
        usedRecordId: usedRecord.id,
        voucherName: voucher.name,
        usedAmount: amountFloat,
        remainingValue: voucher.value - amountFloat
      }
    };
  } catch (error) {
    request.log.error(error);
    return reply.code(500).send({
      code: 500,
      message: '使用卡券失败'
    });
  }
}

// 辅助函数：计算卡券状态
function getVoucherStatus(validStartTime, validEndTime) {
  const now = new Date();
  const startTime = new Date(validStartTime);
  const endTime = new Date(validEndTime);

  if (now < startTime) {
    return '未开始';
  } else if (now > endTime) {
    return '已过期';
  } else {
    return '有效';
  }
}

module.exports = {
  getCoupons,
  createCoupon,
  updateCouponStatus,
  getCouponDetail,
  updateCoupon,
  claimCoupon,
  getUserCoupons,
  useCoupon
};
